<template>
  <div class="warpper">
    <div class="toolbar" style="float: right;">
      <!-- <el-button type="primary" plain @click="add1">+New Sales</el-button> -->
      <el-button type="primary" plain @click="addv" style="margin:0 30px;">+New</el-button>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column prop="id" label="Id" width="50" align="center" />

        <el-table-column prop="nickname" label="Name" align="center" />

        <el-table-column label="Status" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.email === 'admin'" />
            <el-switch v-else v-model="scope.row.status" active-text="ON" inactive-text="OFF"
              @change="changeStatus(scope.row)" />
          </template>
        </el-table-column>


        <el-table-column label="ISsale" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.email === 'admin'" />
            <el-switch v-else v-model="scope.row.usertype" active-text="ON" inactive-text="OFF"
              @change="changeusertype(scope.row)" />
          </template>
        </el-table-column>

        <el-table-column label="Role" align="center">
          <template v-slot="scope">
            <el-tag v-for="(item, index) in scope.row.roles" :key="index" style="margin-right: 10px;">
              {{ item.role_name }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="Tel" align="center" />

        <el-table-column prop="email" label="Account" align="center" />

        <el-table-column label="Avatar" width="80px" align="center">
          <template slot-scope="scope">
            <el-avatar v-if="scope.row.avatar" shape="square" size="medium" :src="scope.row.avatar" />
            <el-avatar v-else shape="square" size="medium" :src="squareUrl" />
          </template>
        </el-table-column>

        <el-table-column label="Action" width="400px" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.email !== 'admin'" plain @click="edit(scope.row.id)">Edit</el-button>
            <el-button v-if="scope.row.email !== 'admin'" plain @click.prevent="updatePassword(scope.row.id)">Reset
              Password</el-button>
            <el-button v-if="scope.row.email !== 'admin'" plain type="danger" @click="del(scope.row.id)">Del</el-button>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="page">
      <el-pagination background :current-page="page.current_page" :page-sizes="page.sizes" :page-size="page.per_page"
        layout="prev, pager, next" :total="page.total" @size-change="sizeChange" @current-change="currentChange" />
    </div>


    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="40%">
      <el-form v-if="dialogFormVisible" ref="ruleForm" :model="formData" :rules="rules">
        <!-- 修复表单自动提交 -->
        <el-input type="password" style="position:fixed;bottom: -9999px;" />
        <el-input type="password" style="position:fixed;bottom: -9999px;" />
        <!-- 这里面开始 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Name" prop="email">
              <el-input v-model="formData.email" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Account" prop="nickname">
              <el-input v-model="formData.nickname" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item v-if="isNew" label="Password" prop="password">
              <el-input v-model="formData.password" type="password" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isNew" label="Password Confirmation" type="password" prop="password_confirmation">
              <el-input v-model="formData.password_confirmation" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Role" prop="roles">
              <el-select v-model="formData.roles" multiple :multiple-limit="1" clearable placeholder="Select roles"
                disabled style="width: 100%" v-if="issale">
                <el-option v-for="item in roles" :key="item.id" :label="item.desc" :value="item.id" v-if="item.id==4" />
              </el-select>

              <el-select v-model="formData.roles" multiple :multiple-limit="1" clearable placeholder="Select roles"
                style="width: 100%" v-else>
                <el-option v-for="item in roles" :key="item.id" :label="item.desc" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Tel" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Avatar" style="margin-bottom: 0px;">
              <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
                :on-change="changeAvatar" :auto-upload="false" :http-request="avatarUpload" name="file">
                <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="IsSale" prop="usertype1">
              <el-switch v-model="formData.usertype1" @change="handleUserTypeChange" />
            </el-form-item>

            <el-form-item label="C-Rate(%)" prop="rate" v-if="formData.usertype1">
              <el-input-number size="mini" v-model="formData.rate" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="saveData()">Save</el-button>
      </div>
    </el-dialog>

    <el-dialog title="Change Password" :visible.sync="dialogFormPasswordVisible" width="30%">
      <el-form>
        <el-form-item label="password">
          <el-input v-model="password" autocomplete="off" type="password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormPasswordVisible = false">cancel</el-button>
        <el-button type="primary" @click="savePassword">Save</el-button>
      </div>
    </el-dialog>
    <UploadXls :show.sync="isShow" :module="module" />
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    update
  } from "@/api/admin";
  import {
    index as getRoles
  } from "@/api/role";
  import {
    store as uploadImg
  } from "@/api/media";
  import UploadXls from "@/components/UploadXls";
  export default {
    name: "AdminIndex",
    components: {
      UploadXls: UploadXls
    },
    mixins: [CURD],
    data() {
      return {
        module: "admin",
        newTitle: "New Account",
        editTitle: "Edit Account",
        imageUrl: "",
        dialogFormPasswordVisible: false,
        password: "",
        id: "",
        roles: [],
        issale: false,
        isUploadFile: false,
        importDialogVisible: false,
        fileReader: new FileReader(),
        isShow: false,
        formData: {
          usertype: false,
          usertype1: false
        },
        squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
      };
    },
    async created() {
      this.issale = false;
      const {
        data
      } = await getRoles();
      this.roles = data;
    },

    methods: {
      add1() {
        this.issale = true;
        this.isNew = true;
        this.isEdit = false;
        this.formData.roles = [4];
        this.dialogFormVisible = true
      },
      addv() {
        this.isNew = true;
        this.isEdit = false;
        this.issale = false;
        this.dialogFormVisible = true
      },
      uploadData() {
        this.isShow = true;
      },
      async edit(id) {
        const {
          show
        } = require(`@/api/${this.module}`);
        const {
          data
        } = await show(id);
        let result = data;
        let arr = [];
        arr = result.roles.map((item) => {
          return item.role_id;
        });
        result.roles = arr;
        this.formData = result;
        console.log(this.formData.roles)
        this.formData.usertype1 = this.formData.usertype == 1 ? true : false
        console.log(this.formData)
        this.isNew = false;
        this.isEdit = true;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      async changeusertype(content) {
        this.$confirm("This operation will modify the user usertype. Do you want to continue?", "prompt", {
            confirmButtonText: "confirm",
            cancelButtonText: "cancel",
            type: "warning"
          })
          .then(async () => {
            const data = {
              id: content.id,
              usertype: content.usertype,
              action: "usertype"
            };
            const {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            // 返回原来的状态
            content.usertype = !content.usertype;
          });
      },
      async changeStatus(content) {
        this.$confirm("This operation will modify the user status. Do you want to continue?", "prompt", {
            confirmButtonText: "confirm",
            cancelButtonText: "cancel",
            type: "warning"
          })
          .then(async () => {
            const data = {
              id: content.id,
              status: content.status ? 1 : 0,
              action: "status"
            };
            const {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            // 返回原来的状态
            content.status = !content.status;
          });
      },
      async avser() {
        //this.formData.usertype = this.formData.usertype ? 1 : 0;
      },
      async handleUserTypeChange(val) {
      this.formData.usertype1 = val;
      this.$forceUpdate(); // 强制更新视图
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.avatar = data.url;
              console.log("vvvvvvvvvvvvvvvvvvv")
              this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      updatePassword(id) {
        this.id = id;
        this.dialogFormPasswordVisible = true;
      },
      async savePassword() {
        if (this.password.length >= 6 && this.password.length <= 20) {
          const data = {
            id: this.id,
            action: "reset",
            password: this.password
          };
          const {
            info
          } = await update(data);
          this.$message.success(info);
          this.dialogFormPasswordVisible = false;
        } else {
          this.$message.error("The password length must be between 6-20 characters");
        }
      },
      changeAvatar(file, fileList) {
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.avatar = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
        };
      },
      saveData() {
        if (this.isUploadFile) {
          this.$refs.uploadAvatar.submit();
        } else {
          console.log("dssssssssssssssssss")
          this.save("ruleForm");
        }
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.usertype = this.formData.usertype1 ? 1 : 0;
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success(info);
              }
              if (this.isNew) {
                console.log("zzzzzzzzzzzzzzzzzzzzz")
                let {
                  store
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await store(this.formData);
                this.$message.success(info);
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
    }
  };
</script>

<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    ;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
  }

  .page {
    text-align: center;
  }

  .el-form table tbody {
    width: 100%;
  }

  .el-form .header {
    box-sizing: border-box;
    border: 1px solid #ccc;
    background-color: #09f;
    color: #fff;
    height: 44px;
    display: flex;
    flex-direction: row;
  }

  .el-form .header .title {
    margin: auto;
    font-weight: bold;
  }

  .el-form .content {
    display: flex;
    box-sizing: border-box;
    border: 1px solid #ccc;
    background-color: #0cf;
    color: #fff;
    height: 44px;
    flex-direction: row;
  }

  .el-form .content div {
    margin: auto;
    border-radius: 0px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>